package com.yunxin.common.utils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * @author zero°
 * @since 2023-06-03
 */
public class SnowflakeKeyGenerator {

    /**
     * 日期格式化-yyyyMMdd
     */
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");

    /**
     * 每一部分占用的位数 ***占用的位数
     */
    private static final long SEQUENCE_BIT = 12;
    /**
     * 机器标识占用的位数
     */
    private static final long MACHINE_BIT = 5;
    /**
     * 数据中心占用的位数
     */
    private static final long DATACENTER_BIT = 5;

    /**
     * 每一部分的最大值
     */
    private static final long MAX_DATACENTER_NUM = ~(-1L << DATACENTER_BIT);
    private static final long MAX_MACHINE_NUM = ~(-1L << MACHINE_BIT);
    private static final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BIT);

    /**
     * 每一部分向左的位移
     */
    private static final long MACHINE_LEFT = SEQUENCE_BIT;
    private static final long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
    private static final long TIMESTAMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;
    /**
     * 起始的时间戳
     */
    private final long startStamp;
    /**
     * 数据中心
     */
    private final long datacenterId;
    /**
     * 机器标识
     */
    private final long machineId;
    /**
     * ***
     */
    private long sequence = 0L;
    /**
     * 上一次时间戳
     */
    private long lastStamp = -1L;

    /**
     * 构造方法
     * @param datacenterId 数据中心
     * @param machineId 机器标识
     */
    public SnowflakeKeyGenerator(long datacenterId, long machineId) {
        if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
            throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");
        }
        if (machineId > MAX_MACHINE_NUM || machineId < 0) {
            throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");
        }
        this.datacenterId = datacenterId;
        this.machineId = machineId;
        this.startStamp = LocalDateTime.of(2023, 1, 1, 0, 0, 0, 0).toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }

    /**
     * 构造方法
     * @param datacenterId 数据中心
     * @param machineId 机器标识
     * @param startStamp 开始时间戳
     */
    public SnowflakeKeyGenerator(long datacenterId, long machineId, Long startStamp) {
        if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
            throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");
        }
        if (machineId > MAX_MACHINE_NUM || machineId < 0) {
            throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");
        }
        this.datacenterId = datacenterId;
        this.machineId = machineId;
        this.startStamp = startStamp;
    }

    /**
     * 生成带前缀的全局唯一key（长度=customerPrefix长度 + yyyyMMdd-8 + generate()-18）
     * @param customerPrefix customerPrefix
     * @return string
     */
    public String generateKey(String customerPrefix) {
        String realPrefix = Objects.nonNull(customerPrefix) ? customerPrefix : "00";
        return realPrefix + LocalDate.now().format(DATE_FORMATTER) + this.generate();
    }

    /**
     * 生成全局唯一key
     * @return long
     */
    public long generateKey(){
        return generate();
    }

    /**
     * 生成全局id
     * @return long
     */
    private synchronized long generate() {
        long currStamp = getNewTimeStamp();
        if (currStamp < lastStamp) {
            throw new IllegalArgumentException("Clock moved backwards.  Refusing to generate id");
        }
        if (currStamp == lastStamp) {
            //相同毫秒内，***自增
            sequence = (sequence + 1) & MAX_SEQUENCE;
            //同一毫秒的序列数已经达到最大
            if (sequence == 0L) {
                currStamp = getNextMill();
            }
        } else {
            //不同毫秒内，***置为0
            sequence = 0L;
        }
        lastStamp = currStamp;
                //时间戳部分
        return (currStamp - startStamp) << TIMESTAMP_LEFT
                //数据中心部分
                | datacenterId << DATACENTER_LEFT
                //机器标识部分
                | machineId << MACHINE_LEFT
                //***部分
                | sequence;
    }

    /**
     * 获取下一个时间戳
     * @return long
     */
    private long getNextMill() {
        long mill = getNewTimeStamp();
        while (mill <= lastStamp) {
            mill = getNewTimeStamp();
        }
        return mill;
    }

    /**
     * 获取新的时间戳
     * @return long
     */
    private long getNewTimeStamp() {
        return System.currentTimeMillis();
    }

}
